<?php

require  'app' . DIRECTORY_SEPARATOR . 'copperforest.commons.php';

define( 'CF_APP_PATH', CF_BASE_PATH . 'app' . DIRECTORY_SEPARATOR );

//tengo que hacer una function que  copie de un directorio a otro recursivamente

function rcopy( $source, $dest ){
    
    mkdir( $dest, 0755 );
    chmod( $dest, 0777 );
    
    foreach (
        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator( $source, \RecursiveDirectoryIterator::SKIP_DOTS ),
            \RecursiveIteratorIterator::SELF_FIRST )
        as $item
    ) {
        if ($item->isDir()) {
            mkdir( $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName() );
        } else {
            copy( $item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
            /*
            if ( !empty( $diffobject ) && defined( 'CF_LAST_BUILD' ) && file_exists( CF_BUILD_PATH . CF_LAST_BUILD . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . $base . $f ) ) {

                //echo '<h3>' . $base . $f . '</h3>' . "\n";

                $diffs = $diffobject->diff_main( file_get_contents( CF_BUILD_PATH . CF_LAST_BUILD . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . $base . $f ),
                        file_get_contents( CF_CLASS_PATH . $base . $f ) );

                $diffobject->diff_cleanupSemantic( $diffs );

                if ( count( $diffs ) > 1 )
                        file_put_contents( CF_CLASS_PATH . $base . $f . '.patch',
                            serialize( $diffs ) );

                unset( $diffs );
            }
            */
        }
    }
}

//ahora tengo que encontrar un build mayor que el que tengo
$dir_handler = opendir( CF_BUILD_PATH );
$last_build = 0;

while ( ( $file = readdir( $dir_handler ) ) !== false ) {

    if ( is_dir( CF_BUILD_PATH . $file ) && preg_match( '/^\d+$/', $file ) ) {

//tengo que hacer otra comprobación, si este build no tuvo errores en su construcción
        if ( !file_exists( CF_BUILD_PATH . $file . DIRECTORY_SEPARATOR . 'build.time' ) )
                rmtree( CF_BUILD_PATH . $file ); //eliminamos ese build

        else if ( $last_build < ( ( int ) $file ) ) $last_build = ( int ) $file;
    }
}

closedir( $dir_handler );

define( 'CF_LAST_BUILD', $last_build );
$_SERVER[ 'CF_BUILD' ] = $last_build + 1;


mkdir( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ], 0777 );
chmod( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ], 0777 );

mkdir( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'src',
        0777 );
chmod( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'src' , 0777 );

mkdir( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'resources',
        0777 );
chmod( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'resources' , 0777 );

mkdir( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'log',
        0777 );
chmod( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'log' , 0777 );

mkdir( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'config',
        0777 );
chmod( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'config' , 0777 );

define( 'CF_CLASS_PATH',
        CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR );

//desplegamos la nueva versión, Primero las librerías, Debería hacer un Patch de la librerías?

if ( file_exists( CF_APP_PATH . 'lib' ) && is_dir( CF_APP_PATH . 'lib' ) ) {

    $libs = array_diff( scandir( CF_APP_PATH . 'lib' ), array( '.', '..' ) );

    foreach ( $libs as $l ) {
        //los archivos pueden ser tar, tar.gz, tgz, bz o bz2 siempre que los modulos de compresion estén disponibles

    //    if()
        
        if ( substr( $l, -4 ) == '.tar'  || substr( $l,
                        -7 ) == '.tar.gz' || substr( $l, -4 ) == '.tgz' || substr( $l,
                        -4 ) == '.bz2' || substr( $l, -3 ) == '.bz' ) { //|| substr( $l, -4 ) == '.zip'


            $phar = new PharData( CF_APP_PATH . 'lib' . DIRECTORY_SEPARATOR . $l );
                        
            $phar->extractTo( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ], null, true );

            unset( $phar );

            

            if ( file_exists( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'build.php' ) ) {
                
                $buildcontent = file_get_contents( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'build.php' );
                
                $posini = strrpos( $buildcontent, '<?');
                $posfin = strrpos( $buildcontent, '?>');
                
                if( $posfin === false || $posfin < $posini ){
                    $buildcontent .= '?>';
                }
                
                file_put_contents( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'buildall.php', $buildcontent, FILE_APPEND );

                unlink( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR .  'build.php' );
                
            }
        }
    }
}

//Solo hago el diff de los archivos de src???


if ( file_exists( CF_APP_PATH . 'build.php' ) ) {
                
    $buildcontent = file_get_contents( CF_APP_PATH . 'build.php' );

    $posini = strrpos( $buildcontent, '<?');
    $posfin = strrpos( $buildcontent, '?>');

    if( $posfin === false || $posfin < $posini ){
        $buildcontent .= '?>';
    }

    file_put_contents( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'buildall.php', $buildcontent, FILE_APPEND );
}



if ( file_exists( CF_APP_PATH  ) && is_dir( CF_APP_PATH ) ) {
    rcopy( CF_APP_PATH . 'src' , CF_CLASS_PATH );
    rcopy( CF_APP_PATH . 'resources' , CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'resources' );
}

//Establecemos el nuevo classPath
spl_autoload_unregister( 'cfFrameworkSrcClassPath' );

function cfFrameworkClassPath( $className )
{

    require_once( CF_CLASS_PATH . str_replace( '\\', DIRECTORY_SEPARATOR,
                    $className ) . '.class.php');
}

spl_autoload_register( 'cfFrameworkClassPath' );


//Antes de esto no debería haber cargado ninguna clase a excepcion de las de org.copperfores.build
if ( file_exists( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR .  'buildall.php' ) ) {
    
    include CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR .  'buildall.php';
    
    unlink( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR .  'buildall.php' );
}


file_put_contents( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'build.time',
        time() ); //Ademas del tiempo deberá guardar que librerías de la anterior compilacion no están presentes